package com.example.myapplication;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;


import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.example.myapplication.camera.CameraActivity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class AddContent extends Activity implements View.OnLongClickListener {//往笔记本里添加内容，即写文字的界面
    private Button locationButton;//获得位置的按钮
    private Button photoButton;
    private TextView locationtext;
    public AMapLocationClient mLocationClient = null;//位置监听器
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private boolean hasGotToken = false;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106;

    private TextView timeText;//记录时间的组件

    private EditText mEt;//组件实例
    private MyDB mDb;//数据库
    private SQLiteDatabase mSqldb;//表实例
    public static final String Url="jdbc:mysql://cdb-l1c6g0ne.bj.tencentcdb.com:10166/AndroidUser?user=root&password=tzyTZY123";
    public static final String Driver="com.mysql.jdbc.Driver";
    private static Connection connection = null;
    private static PreparedStatement preparedStatement = null;
    private static ResultSet resultSet;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //以上代码用来去除黑框
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_content);
        locationButton=(Button)findViewById(R.id.location);
        photoButton=(Button)findViewById(R.id.camera);
        locationButton.setOnLongClickListener(this);//注册监听
        photoButton.setOnLongClickListener(this);
        locationtext=(TextView)findViewById(R.id.LocationText);
        timeText=(TextView)findViewById(R.id.TimeText);
        timeText.setText(getTime());
        locationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动定位
                mLocationClient.startLocation();
                //tv.setText(sHA1(Location.this));
                //Log.e("AmapError",sHA1(Location.this));
            }
        });


        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                //alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());





        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        //获取一次定位结果：
        //该方法默认为false。
        //mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        //mLocationOption.setOnceLocationLatest(true);

        //连续多次定位（不能与一次定位兼得）
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。设置定位请求超时时间，默认为30秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        //mLocationClient.startLocation();
        mEt = (EditText) this.findViewById(R.id.text);
        mDb = new MyDB(this);
        mSqldb = mDb.getWritableDatabase();//增加可写表
    }









    public void saveClick(View v) throws SQLException, ClassNotFoundException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                int NoteNo=0;
                List<String> result=new ArrayList<>();
                String ContentText=mEt.getText().toString();
                String NowTime=getTime();
                String username=LoginWithanim.LoginUserName;
                String MySql = "select * from Note";//查询元素个数
                String MySql2 = "insert into Note(UserName,NoteNo,Content,Location) values(?,?,?,?)";//插入数据
                try {
                    Class.forName(Driver);
                    //2.创建连接
                    connection = DriverManager.getConnection(Url);
                    preparedStatement = connection.prepareStatement(MySql);
                    resultSet =  preparedStatement.executeQuery();
                    while(resultSet.next()){
                        NoteNo++;//笔记本个数
                    }
                    String LocationSQL=locationtext.getText().toString();//暂时没想好咋写
                    preparedStatement = connection.prepareStatement(MySql2);
                    preparedStatement.setString(1, username);
                    preparedStatement.setString(2, String.valueOf(NoteNo));
                    preparedStatement.setString(3, ContentText);
                    if (LocationSQL.length()<20){
                        preparedStatement.setString(4,"?");
                    }
                    else{
                        preparedStatement.setString(4, LocationSQL.substring(LocationSQL.length()-30,LocationSQL.length()-2));
                    }
                    preparedStatement.executeUpdate();
                } catch (SQLException | ClassNotFoundException throwables) {
                    throwables.printStackTrace();
                }
            }
        }).start();
        
        DbAdd();//调用下面的函数
        finish();
    }
    public void cancleClick(View v) {
        mEt.setText("");
        finish();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    String address;
                    //可在其中解析amapLocation获取相应内容。
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    amapLocation.getLatitude();//获取纬度
                    amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    address = amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    address += amapLocation.getCountry();//国家信息
                    address += amapLocation.getProvince();//省信息
                    address += amapLocation.getCity();//城市信息
                    address += amapLocation.getDistrict();//城区信息
                    address += amapLocation.getStreet();//街道信息
                    address += amapLocation.getStreetNum();//街道门牌号信息
                    address += amapLocation.getCityCode();//城市编码
                    address += amapLocation.getAdCode();//地区编码
                    address += amapLocation.getAoiName();//获取当前定位点的AOI信息
                    address += amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                    address += amapLocation.getFloor();//获取当前室内定位的楼层
                    address += amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
                    //获取定位时间
                    System.out.println(address);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);
                    locationtext.setText(address);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };


    public void DbAdd() {//加入数据库
        ContentValues cv = new ContentValues();//代插入的值
        cv.put(MyDB.CONTENT,mEt.getText().toString());//设置内容
        cv.put(MyDB.TIME,getTime());//设置时间
        cv.put(MyDB.LOCATION,locationtext.getText().toString());
        mSqldb.insert(MyDB.TABLE_NAME,null,cv);//插入数据库
    }


    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recGeneralBasic(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            Gson gson=new Gson();
                            Word_List_Camera temp=gson.fromJson(result,Word_List_Camera.class);
                            mEt.setText(mEt.getText()+temp.toString());//在这里加json
                        }
                    });
        }
    }

    public void getCamera(View view){
    //general_basic_button
        if (!checkTokenStatus()) {
            return;
        }
        Intent intent = new Intent(AddContent.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);
    }

    public String getTime() {//获得当前时间并转化成字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = new Date();
        String str = sdf.format(date);
        return str;
    }


    @Override
    public boolean onLongClick(View v) {
        if(v==locationButton){
            startActivity(new Intent(AddContent.this,MyMap.class));
        }
        else if(v==photoButton){
            startActivity(new Intent(AddContent.this,MyCamera.class));
        }
        return false;
    }
}
